package com.lotusfall.controller;

import com.lotusfall.pojo.Student;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisController {

    /**
     *  注入RedisTemplate
     *
     *  RedisTemplate 泛型
     *  RedisTemplate<String,String>
     *  RedisTemplate<Object,Object>
     *  RedisTemplate
     *
     *  注意 ：对象的名称 redisTemplate
     */

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 添加数据到redis
    @PostMapping("/redis/addstring")
    public String addToRedis(String name,String value){

        // 操作Redis中string类型的数据，现货区ValueOperation对象
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("myname","lisi");
        return "向redis添加String数据";
    }

    // 从redis中获取数据
    @GetMapping("/redis/get")
    public String getString(String k){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object o = valueOperations.get(k);
        return k + "==" + o;
    }


    // 添加数据到redis
    @PostMapping("/redis/{k}/{v}")
    public String addStringKV(@PathVariable String k,@PathVariable String v){
        stringRedisTemplate.opsForValue().set(k,v);
        return "使用stringRedisTemplate添加数据";
    }

    // 添加数据到redis
    @GetMapping("/redis/getstr/{k}")
    public String getStringValue(@PathVariable String k){

        return k + "=" + stringRedisTemplate.opsForValue().get(k) + "/n使用stringRedisTemplate添加数据";
    }

    @PostMapping("/redis/addjson")
    public String addJson(){
        Student student = new Student("张三","北大",20);

        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 把值作为json序列化
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Student.class));
        redisTemplate.opsForValue().set("mystudent",student);
        return "json序列化";
    }
    @PostMapping("/redis/getjson")
    public String getJson(){
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 把值作为json序列化
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Student.class));
        Object mystudent = redisTemplate.opsForValue().get("mystudent");
        return "json反序列化=" + mystudent;
    }

}
